﻿
namespace EasyNet.Solr.Impl
{
    using System.Collections.Generic;
    using System.Linq;
    using System.Xml.Linq;

    public class XmlFacetFieldsParser : ISolrResponseParser<string, IDictionary<string, IList<FacetField>>>
    {
        public IDictionary<string, IList<FacetField>> Parse(string result)
        {
            if (string.IsNullOrEmpty(result))
            {
                return null;
            }

            var xmlDoc = XDocument.Parse(result);

            var facetCounts = from e in xmlDoc.Root.Elements("lst")
                              where (string)e.Attribute("name") == "facet_counts"
                              select e;

            if (facetCounts == null)
            {
                return null;
            }

            var facetFields = from e in facetCounts.Elements("lst")
                              where (string)e.Attribute("name") == "facet_fields"
                              select e;

            if (facetFields == null)
            {
                return null;
            }

            var facetFieldsResult = new Dictionary<string, IList<FacetField>>(facetFields.Single().Elements().Count());

            foreach (var element in facetFields.Single().Elements())
            {
                var fieldName = element.Attribute("name").Value;

                if (!facetFieldsResult.ContainsKey(fieldName))
                {
                    facetFieldsResult.Add(fieldName, new List<FacetField>());
                }

                foreach (var facetFieldEl in element.Elements())
                {
                    facetFieldsResult[fieldName].Add(new FacetField() { Name = facetFieldEl.Attribute("name").Value, Count = int.Parse(facetFieldEl.Value) });
                }
            }

            return facetFieldsResult;
        }
    }
}
